package com.zzt.appframe8.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;

import androidx.annotation.NonNull;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.view.ViewCompat;

import com.google.android.material.internal.CheckableImageButton;
import com.google.android.material.textfield.TextInputLayout;
import com.google.android.material.textfield.TextInputLayout.BoxBackgroundMode;

import java.util.Arrays;

/**
 * End icon delegate abstract class.
 * Each end icon delegate class that extends this class will provide the default configuration for
 */
abstract class EndIconDelegate {

    MTextInputLayout textInputLayout;
    Context context;

    EndIconDelegate(@NonNull MTextInputLayout textInputLayout) {
        this.textInputLayout = textInputLayout;
        context = textInputLayout.getContext();
    }

    /**
     * Default configurations for the specified end icon.
     */
    abstract void initialize();

    /**
     * Whether the end icon should be tinted with the error color when the {@link TextInputLayout} is
     * in error mode.
     */
    boolean shouldTintIconOnError() {
        return false;
    }


    void setTintIconOnError(int mErrorTextColor) {

    }


    /**
     * 根据状态设置按钮颜色
     *
     * @param iconView
     * @param colorStateList
     */
    public void refreshIconDrawableState(CheckableImageButton iconView, ColorStateList colorStateList) {
        Drawable icon = iconView.getDrawable();
        if (iconView.getDrawable() == null || colorStateList == null || !colorStateList.isStateful()) {
            return;
        }

        int color = colorStateList.getColorForState(mergeIconState(iconView), colorStateList.getDefaultColor());

        icon = DrawableCompat.wrap(icon).mutate();
        DrawableCompat.setTintList(icon, ColorStateList.valueOf(color));
        iconView.setImageDrawable(icon);
    }

    /**
     * 设置按钮状态
     *
     * @param iconView
     * @return
     */
    public int[] mergeIconState(CheckableImageButton iconView) {
        int[] textInputStates = textInputLayout.getDrawableState();
        int[] iconStates = iconView.getDrawableState();

        int index = textInputStates.length;
        int[] states = Arrays.copyOf(textInputStates, textInputStates.length + iconStates.length);

        System.arraycopy(iconStates, 0, states, index, iconStates.length);

        return states;
    }

    /**
     * 设置按钮状态
     *
     * @param iconView
     */
    @SuppressLint("RestrictedApi")
    public static void setIconClickable(@NonNull CheckableImageButton iconView) {
        boolean iconClickable = ViewCompat.hasOnClickListeners(iconView);
        iconView.setFocusable(iconClickable);
        iconView.setClickable(iconClickable);
        iconView.setPressable(iconClickable);
    }
}
